package org.bud.db.dynamic.base;

import lombok.extern.slf4j.Slf4j;
import org.bud.db.dynamic.config.ApplicationHolder;

import javax.sql.DataSource;
import java.util.Objects;

/**
 * @author shaun
 * @date 2025/4/1
 * @instruction
 */
@Slf4j
public abstract class DynamicDataSourceHolder {

    private static final ThreadLocal<Object> TL_DYNAMIC_DB_SOURCE = new ThreadLocal<Object>(){
        @Override
        protected Object initialValue() {
            DynamicDataSource dynamicDataSource = ApplicationHolder.getBean(DynamicDataSource.class);
            DataSource resolvedDefaultDataSource = dynamicDataSource.getResolvedDefaultDataSource(dynamicDataSource);
            if(Objects.isNull(resolvedDefaultDataSource)){
                throw new IllegalArgumentException("Dynamic data source not set the default target datasource");
            }
            if(resolvedDefaultDataSource instanceof DynamicVSource ){
                return ((DynamicVSource) resolvedDefaultDataSource).getAlias();
            }
            throw new IllegalArgumentException("Dynamic data source not set the alias");
        }
    };

    public static void setDS(Object dbType){
        log.info("set to db : {}",dbType);
        TL_DYNAMIC_DB_SOURCE.set(dbType);
    }

    public static Object get(){
        return TL_DYNAMIC_DB_SOURCE.get();
    }

    public static void clear(){
        log.info("clear db : {}",get());
        TL_DYNAMIC_DB_SOURCE.remove();
    }


}
